var _treeDatagrid,dialogAddRow,formAddRow,id,pid,name,type,msgReplyId,url,msgType;

function addRow(o) {
	if (o) {
		_treeDatagrid.treegrid('select', o);
	}
	addRowHandler();
}

function addRowHandler() {
	var node = _treeDatagrid.treegrid('getSelections');
		id.val(0);
		if(!node || node.length <= 0){
			pid.val(0);
			if(_treeDatagrid.treegrid('getChildren', 0).length >=3){
				$.messager.alert('提示', '目前一级菜单个数最多为3个!', 'warning');
				return ;
			}
		}else{
			pid.val(node[0].id);
			if(_treeDatagrid.treegrid('getParent', node[0].id) != null ){
				$.messager.alert('提示', '目前仅支持二级菜单！', 'warning');
				return ;
			}
			if(_treeDatagrid.treegrid('getChildren', node[0].id).length >=5){
				$.messager.alert('提示', '目前子菜单个数最多为5个!', 'warning');
				return ;
			}
		}
		type.combobox('setValue', '');
		msgReplyId.combogrid('setValue', '');
		$('#name').val('');
		url.val(''); 
		dialogAddRow.dialog({title:'添加微信菜单',iconCls:'icon-add',buttons:[{text:'添加',handler:dialogEnterHandler}]});
		var data = type.combobox('getData');
		type.combobox('setValue',data[0].code).combobox('setText',data[0].name);
		dialogAddRow.dialog('open');
}

function deleteRow(o) {
	if (o) {
		_treeDatagrid.treegrid('select', o);
	}
	deleteRowHandler();
}

function deleteRowHandler() {
	var node = _treeDatagrid.treegrid('getSelections');
	if (node && node.length > 0) {
		$.messager.confirm('请确认', '您确实要删除当前所有选择的记录吗？注意：此操作将删除所有子机构！！！', function(b){
			if (b) {
				var ids = [];
				for ( var i = 0; i < node.length; i++) {
					ids.push(node[i].id);
				}
				$.post(sy.bp()+"/admin/weixin/menu/delete", {ids:ids.join(",")}, function(data) {
					if (data.result==1) {
						$.messager.show({msg:data.msg,title:'系统提示'});
						_treeDatagrid.treegrid('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要删除的记录', 'error');
	}
}

function updateRow(o) {
	if (o) {
		_treeDatagrid.treegrid('select', o);
	}
	updateRowHandler();
}

function updateRowHandler() {
	var node = _treeDatagrid.treegrid('getSelections');
	if (node && node.length > 0) {
		if (node.length > 1) {
			$.messager.alert('提示', '您选择了多个菜单项,只能选择一个菜单项！', 'warning');
			_treeDatagrid.treegrid('unselectAll');
		} else {
			id.val(node[0].id);
			pid.val(node[0].pid);
			if(node[0].pid == 0){
				type.combobox({required:false,editable:false});
			}
			type.combobox('setValue',node[0].type);
			msgReplyId.combogrid('setValue', node[0].msgReplyId);
			$('#name').val(node[0].name);
			url.val(node[0].url); 
			dialogAddRow.dialog({title:'更新菜单项',iconCls:'icon-edit',buttons:[{text:'更新',handler:dialogEnterHandler}]});
			dialogAddRow.dialog('open');
		}
	} else {
		$.messager.alert('提示', '您没有选择菜单项,请选择！', 'warning');
	}
}

function createRow(o) {
	if (o) {
		_treeDatagrid.treegrid('select', o);
	}
	createRowHandler();
}

function createRowHandler() {
	$.post(sy.bp() + "/admin/weixin/menu/create",null, function(data){
		if(data && data.result ==1) {
			dialogAddRow.dialog('close');
			$.messager.show({title:'系统提示', msg:data.msg, timeout:2000, showType:'slide'});
			_treeDatagrid.treegrid('reload');
		} else {
			$.messager.alert('错误提示', data.msg);
		}
	},"json");
}

function reloadRow() {
	_treeDatagrid.treegrid('reload');
}

function unselectRow() {
	_treeDatagrid.treegrid('unselectAll');
}

/**添加或更新对话框*/
function dialogEnterHandler() {
//	if (formAddRow.form('validate')) {
		var url = sy.bp() + '/admin/weixin/menu/';
		if (id.val() == 0) {
			url += 'add';
		} else {
			url += 'update';
		}
		$.post(url, $('#formAddRow').serialize(), function(data){
			if(data && data.result ==1) {
				dialogAddRow.dialog('close');
				$.messager.show({title:'系统提示', msg:data.msg, timeout:2000, showType:'slide'});
				_treeDatagrid.treegrid('reload');
			} else {
				$.messager.alert('错误提示', data.msg);
			}
		},"json");
//	}
}

$(function() {
	_treeDatagrid = $('#_treeDatagrid');
	dialogAddRow = $('#dialogAddRow');
	formAddRow = $('#formAddRow');
	id = $('#id');
	pid = $('#pid');
	name = $('#name').validatebox({required:true,validType:['maxLength[7]']});
	type = $('#type').combobox({required:true,editable:false,valueField:'code',textField:'name',url:sy.bp()+'/admin/dictionary/listDictionary?name=微信菜单',
		onChange:function(newValue, oldValue) {
			if (newValue == 'click') {
				$('#msgReplyId1').show();
				$('#url1').hide();
			} else if(newValue == 'view'){
				$('#msgReplyId1').hide();
				$('#url1').show();
				msgReplyId.combogrid('setValue',0);
			} else {
				$('#msgReplyId1').hide();
				$('#url1').hide();
				msgReplyId.combogrid('setValue',0);
			}
		}
	}).combobox('activeTextArrow');
	msgType = $('#msgType').combobox({required:true,editable:false,valueField:'code',textField:'name',url:sy.bp()+'/admin/dictionary/listDictionary?name=微信回复消息'}).combobox('activeTextArrow');
	$('#msgType1').hide();
	msgReplyId = $('#msgReplyId').combogrid({panelWidth:430,idField:'id',textField:'msgType',pagination:true,singleSelect:true,fitColumns:true,border:false,
		pageSize:10,pageList:[10,20,30,40,50],sortName:'id',sortOrder:'desc',view:sy.myview,emptyMsg:'没有查询到相关数据',url:sy.bp()+'/admin/weixin/replyMsg/list',
		columns:[[
		  {field:'id',hidden:true},
		  {field:'sendMsg',title:'接收消息',align:'left',width:100,sortable:true},
          {field:'msgType',title:'返回类型',align:'left',width:100,sortable:true,
          	formatter:function(value, row) {
          		var data = msgType.combobox('getData');
        		for ( var i = 0; i < data.length; i++) {
					if (value == data[i].code) {
						return data[i].name;
					}
				}
        	}
          },
          {field:'createTime',title:'上传时间',width:200,sortable:true}
        ]]  
	}).combogrid('activeTextArrow');
	url = $('#url').validatebox({required:true,validType:['url','maxLength[255]']});
	dialogAddRow.show().dialog({resizable:false,closed:true,closable:true,modal:true});

	_treeDatagrid.treegrid({   
	    url: sy.bp()+'/admin/weixin/menu/listTreegrid',
	    idField:'id',
	    treeField:'name',
	    fit : true,
		autoRowHeight : true,
		striped : true,
		rownumbers : true,
		singleSelect : true,
		fitColumns : true,
		nowrap : false,
		border : false,
		toolbar: [
					{text:'增加',iconCls: 'icon-add',handler: addRowHandler},'-',
					{text:'删除',iconCls: 'icon-remove',handler: deleteRowHandler},'-',
					{text:'修改',iconCls: 'icon-edit',handler: updateRowHandler},'-',
					{text:'取消选中',iconCls: 'icon-redo',handler: unselectRow},'-',
					{text:'刷新',iconCls: 'icon-reload',handler: reloadRow},'-',
					{text:'创建',iconCls: 'icon-application_view_tile',handler: createRowHandler},'-'
				 ],
		frozenColumns: [[]],
	    columns:[[
	  	    {field:'name',title:'菜单名',width:200,align:'left'},
	        {field:'type',title:'动作类型',width:100,align:'left',formatter:function(value, row) {
          		var data = type.combobox('getData');
        		for ( var i = 0; i < data.length; i++) {
					if (value == data[i].code) {
						return data[i].name;
					}
				}
        	}},
	        //{field:'key',title:'菜单Key',width:100,align:'left'},
	        //{field:'media_id',title:'media_id',align:'left',width:100},
	        {field:'url',title:'url',align:'left',width:200},
	        {field:'msgReplyType',title:'响应类型',width:100,align:'left',formatter:function(value, row) {
          		var data = msgType.combobox('getData');
        		for ( var i = 0; i < data.length; i++) {
					if (value == data[i].code) {
						return data[i].name;
					}
				}
        	}},
	        {field:'msgReplyText',title:'返回文本信息',width:300,align:'left'}
	    ]],
	    onBeforeExpand : function(){
	    },
	    onLoadSuccess : function(data) {
			$.messager.progress('close');
		},
		onDblClickRow : function(row){
			if (row.id > 0) {
				updateRow(row.id);
			} else {
				_treeDatagrid.treegrid('toggle', row.id);
			}
		},
		onContextMenu : function(e, row){
			_treeDatagrid.treegrid('unselectAll');
			_treeDatagrid.treegrid('select', row.id);
			e.preventDefault();
			$('#treeridContextMenu').menu('show', {left:e.pageX,top:e.pageY});
		}
	});
});
